﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace MatrixControls
{
	[DefaultEvent("Click")]
	public partial class PixelBox: UserControl
    {
		private int boxsize      = 20;
		private bool hovered     = false;
		private Color color_fill = Color.White;
		private Color color_mask = Color.FromArgb(103, 103, 103);


		public PixelBox()
        {
            InitializeComponent();

			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);

			BoxSize = boxsize;
		}


		#region 控件属性
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public new Size Size { get; set; }

		[Category("外观")]
		[Description("盒子尺寸大小")]
		public int BoxSize
		{
			get { return boxsize; }
			set
			{
				if (value < 20)
					throw new ArgumentException("BoxSize 不能小于 20 像素");

				Width = Height = boxsize = value;
				Invalidate();
			}
		}

		[Category("外观")]
		[Description("盒子填充颜色")]
		public Color BoxColor
		{
			get { return color_fill; }
			set
			{
				color_fill = value;
				Invalidate();
			}
		}

		[Category("数据")]
		[Description("盒子索引序号")]
		public int Index { get; set; } = 0;

		[Category("数据")]
		[Description("盒子颜色索引序号")]
		public int ColorIndex { get; set; } = 0;

		[Category("外观")]
		[Description("盒子遮罩颜色")]
		public Color MaskColor
		{
			get { return color_mask; }
			set
			{
				color_mask = value;
				Invalidate();
			}
		}
		#endregion


		#region 窗体控件事件
		private void PixelBox_MouseLeave(object sender, EventArgs e)
		{
			hovered = false;
			Invalidate();
		}

		private void PixelBox_MouseEnter(object sender, EventArgs e)
		{
			hovered = true;
			Invalidate();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);

			BufferedGraphicsContext buffer_context = BufferedGraphicsManager.Current;
			BufferedGraphics buffer = buffer_context.Allocate(e.Graphics, e.ClipRectangle);
			Graphics graphics = buffer.Graphics;
			Color brush_color = color_fill;

			if (hovered)
			{
				brush_color = Color.FromArgb(
					(brush_color.R + MaskColor.R) / 2,
					(brush_color.G + MaskColor.G) / 2,
					(brush_color.B + MaskColor.B) / 2
				);
			}

			graphics.FillRectangle(new SolidBrush(brush_color), new Rectangle(0, 0, Width, Height));

			buffer.Render(e.Graphics);
			buffer.Dispose();
			graphics.Dispose();
		}
		#endregion
	}
}
